// pages/login/index.js
const { UserManager, UserRole } = require('../../models/user.js');

Page({
  data: {
    userInfo: null,
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    isRegistering: false,
    formData: {
      name: '',
      phone: '',
      department: '',
      position: ''
    },
    departments: ['技术部', '产品部', '市场部', '人事部', '财务部', '行政部'],
    positions: ['员工', '主管', '经理', '总监', '总经理']
  },

  onLoad() {
    // 检查是否可以使用 getUserProfile API
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }

    // 检查是否已登录
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
      this.navigateBack();
    }
  },

  // 获取用户信息（新接口）
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.processLogin(res.userInfo);
      },
      fail: (err) => {
        console.error('获取用户信息失败', err);
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取用户信息（旧接口，兼容）
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.processLogin(e.detail.userInfo);
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      });
    }
  },

  // 处理登录逻辑
  processLogin(userInfo) {
    const app = getApp();
    const userManager = new UserManager();
    
    // 查找是否已有该用户
    const users = userManager.getUsers();
    const existingUser = users.find(u => u.openId === userInfo.openId || u.nickName === userInfo.nickName);
    
    if (existingUser) {
      // 已注册用户，直接登录
      app.globalData.userInfo = existingUser;
      app.globalData.userRole = existingUser.role;
      
      this.setData({
        userInfo: existingUser,
        hasUserInfo: true
      });
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      this.navigateBack();
    } else {
      // 新用户，显示注册表单
      this.setData({
        tempUserInfo: userInfo,
        isRegistering: true
      });
    }
  },

  // 表单输入处理
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 选择器变化处理
  onPickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    if (field === 'department') {
      this.setData({
        'formData.department': this.data.departments[value]
      });
    } else if (field === 'position') {
      this.setData({
        'formData.position': this.data.positions[value]
      });
    }
  },

  // 提交注册
  submitRegistration() {
    const { formData, tempUserInfo } = this.data;
    
    // 表单验证
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.phone.trim() || !/^1\d{10}$/.test(formData.phone)) {
      wx.showToast({
        title: '请输入有效的手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.department) {
      wx.showToast({
        title: '请选择部门',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.position) {
      wx.showToast({
        title: '请选择职位',
        icon: 'none'
      });
      return;
    }
    
    // 创建新用户
    const userManager = new UserManager();
    const newUser = userManager.createUser({
      ...tempUserInfo,
      realName: formData.name,
      phone: formData.phone,
      department: formData.department,
      position: formData.position,
      role: UserRole.USER // 默认为普通用户
    });
    
    // 更新全局数据
    const app = getApp();
    app.globalData.userInfo = newUser;
    app.globalData.userRole = newUser.role;
    
    this.setData({
      userInfo: newUser,
      hasUserInfo: true,
      isRegistering: false
    });
    
    wx.showToast({
      title: '注册成功',
      icon: 'success'
    });
    
    this.navigateBack();
  },

  // 返回上一页或首页
  navigateBack() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack();
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      });
    }
  },

  // 取消注册
  cancelRegistration() {
    this.setData({
      isRegistering: false,
      tempUserInfo: null
    });
  }
});